var tabNum = 0; //tab页页签
var picture = ''; //设置默认人物头像图片
$(function () {
    console.log(3333)
    init()

    function init() {
        // console.log(22222);
        //创建地图
        map = L.map('mastDt', {
            crs: L.CRS.CustomEPSG4326,
            center: {
                lon: 120.87483,
                lat: 30.039105
            },
            zoom: 14,
            inertiaDeceleration: 15000,
            maxZoom: 20
        });
        //添加栅格底图
        var layer = new L.GXYZ(
            'https://ditu.zjzwfw.gov.cn:443/mapserver/vmap/zjvmap/getMAP?x={x}&y={y}&l={z}&styleId=tdt_kejiganyangshi_2017&token=88eca0c9-1868-4d92-aa49-f0c2144c0e41'
        );
        map.addLayer(layer);
        //添加矢量底图标记
        var labelLayer = new L.GWVTAnno({
            tileSize: 512
        });
        var dataSource = new Custom.URLDataSource();
        dataSource.url =
            'https://ditu.zjzwfw.gov.cn:443/mapserver/label/zjvmap/getData?x={x}&y={y}&l={z}&styleId=tdt_biaozhunyangshi_2017&token=89501c123640e74cad48c088792f94b5';
        labelLayer.addDataSource(dataSource);
        map.addLayer(labelLayer);

        // 监听 mousemove 事件
        // map.on('mousemove', (e) => {
        //     let latlng = e.latlng;
        //     var html = latlng.lat+','+latlng.lng;
        //     L.popup()
        //         .setLatLng([latlng.lat, latlng.lng])
        //         .setContent(html)
        //         .openOn(map);
        //     // console.log(latlng );
        // });
    }
    pointLoad(); // 描点

    // $('#button').on('click', function () {
    //     clickSearchPIO();
    // });

    //点击搜索tab页
    // $('.search_tab a').click(function () {
    //     tabNum = $('.search_tab a').index(this);
    //     $('#searchOptions').html('');
    //     $('#searchOptions').css('display', 'none');
    //     $(this).attr('class', 'cur');
    //     $(this).siblings().attr('class', '');
    // });
});

var keyword = ''; //设置变量保存搜索框的值
var html = ''; //拼接的选项
var dataList = []; //搜索结果集合
var timeout; //设置输入框搜索的定时时间
var center = {};
let zoom = 12;
var map; //创建地图
var markers; //地图上标点的集合


//页面刷新后点加载方法   就这个 ok
function pointLoad() {
    // $.ajax({
    //     url: '../js/digitalPlatform/interfacelocation.json',
    //     type: 'GET',
    //     dataType: 'JSON',
    //     success: function (data) {
    const data = {
        "status": "ok",
        "totalCount": 2218671,
        "pageNum": 0,
        "pageSize": 0,
        "totalPage": 0,
        "results": [{
            "id": "10010",
            "sign": "true",
            "belongCity": "嘉兴市",
            "belongCounty": "海宁市",
            "belongVillage": "硖石街道",
            "llzName": "对全民健身提升工程的意见",
            "address": "浙江省嘉兴市海宁市阆声路(海宁鹃湖公园)文化广场",
            "lon": "120.883454",
            "lat": "30.030966",
            "image": "",
            "principal": "林友珍",
            "phone": "13806728016",
        }]
    }
    //点聚合
    markers = L.markerClusterGroup({ //创建加载点位的变量
        maxClusterRadius: 60,
        disableClusteringAtZoom: 18,
        //Disable all of the defaults:
        spiderfyOnMaxZoom: false,
        showCoverageOnHover: false,
        zoomToBoundsOnClick: false
    });
    console.log(data);
    dataList = data.results;
    $.each(data.results, function (index, val) {
        var lat = val.lat; //点的纬度
        var lon = val.lon; //点的经度
        if (lat && lon) {
            var myIcon = L.icon({
                iconUrl: './img/marker-icon.png',
                iconSize: [25, 41],
                iconAnchor: [15, 40]
            });
            let marker = L.marker([lat, lon], {
                icon: myIcon
            });
            marker.on('click', () => {
                handleMapMarerClick(val)
            });
            markers.addLayer(marker);
        }
        map.addLayer(markers);
        // $("#searchOptions").html(html);
    });
    //     }
    // })

}

//拼接标点信息
function handleMapMarerClick(val) {
    //获取联络站的名称
    var llzName = val.llzName;
    //
    if (tabNum == 0) {
        //tab页切换问题
        $('#province').css('display', 'none');
        provTab();

        //查询代表信息
        $.ajax({
            url: './js/digitalPlatform/representative.json',
            type: 'GET',
            dataType: 'JSON',
            success: function (data) {
                $.each(data.results, function (index, value) {
                    if (llzName && value.pLlz && llzName == value.pLlz) {
                        //获取代表的级别
                        var pRealResp = value.pRealResp;
                        if (pRealResp && pRealResp == '省级代表') {
                            if (val.resp.level1 && val.resp.level1.length < 1) {
                                val.resp.level1.push(value);
                            }
                        }
                        if (pRealResp && pRealResp == '市人大代表') {
                            if (val.resp.level2 && val.resp.level2.length < 1) {
                                val.resp.level2.push(value);
                            }
                        }
                        if (pRealResp && pRealResp == '县人大代表') {
                            if (val.resp.level3 && val.resp.level3.length < 1) {
                                val.resp.level3.push(value);
                            }
                        }
                        if (pRealResp && pRealResp == '镇人大代表') {
                            if (val.resp.level4 && val.resp.level4.length < 1) {
                                val.resp.level4.push(value);
                            }
                        }
                    }
                });
                //代表信息匹配加载
                loadResp(val.resp);
            }
        });

        // console.log(val);
        if (val.image && val.image.length > 0) {
            $('#llzImage').html('<img src=' + val.image + ' />');
        }
        $('.llzName').html(val.llzName);
        $('#address').html(val.address);
        $('#principal').html(val.principal);
        $('#phone').html(val.phone);
        $('#date').html(val.date);
        // $(".float-2").css("display","none");
        // $(".float-3").css("display","none");
        if (val.sign && val.sign == 'true') {
            $('.float-1').css('display', 'block');
        }

        // setTimeout(function () {
        //     L.popup()
        //         .setLatLng([val.location.lat, val.location.lon])
        //         .setContent(val.llzName)
        //         .openOn(map);
        // },0)
    }
    setTimeout(function () {
        var name = val.name;
        if (name != '' && name != undefined) {} else {
            name = val.llzName;
        }
        L.popup().setLatLng([val.lat, val.lon]).setContent(name).openOn(map);
    }, 50);
    // map.setView([val.location.lat, val.location.lon],map.getZoom());
}

//代表信息加载
function loadResp(resp) {
    let sty = 10; //控制tab页切换css样式
    //省级代表加载
    if (undefined != resp && '' != resp) {
        if (resp.level1 && resp.level1.length > 0) {
            sty = 1;
            $('#tab1').css('display', 'block');
            $('#province').css('display', 'none');
            // provTab();
            var prov = resp.level1;
            let province = '';
            for (let item of prov) {
                picture = item.pHeadicon;
                if (picture != '' && picture != undefined && picture != 0) {} else {
                    picture = '../sjglpthtml/css/images/db_icon.png';
                }

                // console.log(image);
                province +=
                    ` <div class="db_info" item-id=${item.id} onclick="dbInfo(this)"><img src="` +
                    picture +
                    `" width="60" />
            <p>${item.pName}</p>
            </div>`;
            }
            $('#province').html(province);
            // $.parser.parse("#province");
        } else {
            $('#tab1').css('display', 'none');
            // $("#province").html('<div class="no-data" style="padding-top:15px;">暂无我们的代表</div>');
        }
        //市级代表加载
        if (resp.level2 && resp.level2.length > 0) {
            if (sty > 2) {
                sty = 2;
            }
            $('#tab2').css('display', 'block');
            $('#city').css('display', 'none');
            // cityTab();
            var city = resp.level2;
            console.log(resp.level2);
            let ci = '';
            for (let item of city) {
                picture = item.pHeadicon;
                if (picture != '' && picture != undefined && picture != 0) {} else {
                    picture = '../sjglpthtml/css/images/db_icon.png';
                }
                // console.log(image);
                ci +=
                    ` <div class="db_info" item-id=${item.id} onclick="dbInfo(this)"><img src="` +
                    picture +
                    `" width="60" />
            <p>${item.pName}</p>
            </div>`;
            }
            $('#city').html(ci);
            // $.parser.parse("#city");
        } else {
            $('#tab2').css('display', 'none');
            // $("#city").html('<div class="no-data" style="padding-top:15px;">暂无我们的代表</div>');
        }

        //乡级代表加载
        if (resp.level3 && resp.level3.length > 0) {
            if (sty > 3) {
                sty = 3;
            }
            $('#tab3').css('display', 'block');
            $('#county').css('display', 'none');
            // countyTab();
            var county = resp.level3;
            let co = '';
            for (let item of county) {
                picture = item.pHeadicon;
                if (picture != '' && picture != undefined && picture != 0) {} else {
                    picture = '../sjglpthtml/css/images/db_icon.png';
                }
                // console.log(image);
                co +=
                    ` <div class="db_info" item-id=${item.id} onclick="dbInfo(this)"><img src="` +
                    picture +
                    `" width="60" />
            <p>${item.pName}</p>
            </div>`;
            }
            $('#county').html(co);
            // $.parser.parse("#county");
        } else {
            $('#tab3').css('display', 'none');
            // $("#county").html('<div class="no-data" style="padding-top:15px;">暂无我们的代表</div>');
        }

        //镇级代表加载
        if (resp.level4 && resp.level4.length > 0) {
            if (sty > 4) {
                sty = 4;
            }
            $('#tab4').css('display', 'block');
            $('#village').css('display', 'none');
            // villageTab();
            var village = resp.level4;
            let vill = '';
            for (let item of village) {
                picture = item.pHeadicon;
                if (picture != '' && picture != undefined && picture != 0) {} else {
                    picture = '../sjglpthtml/css/images/db_icon.png';
                }
                // console.log(image);
                vill +=
                    ` <div class="db_info" item-id=${item.id} onclick="dbInfo(this)"><img src="` +
                    picture +
                    `" width="60" />
            <p>${item.pName}</p>
            </div>`;
            }
            $('#village').html(vill);
            // $.parser.parse("#village");
        } else {
            $('#tab4').css('display', 'none');
            // $("#village").html('<div class="no-data" style="padding-top:15px;">暂无我们的代表</div>');
        }

        // 控制tab页css样式
        if (sty == 1) {
            provTab();
        } else if (sty == 2) {
            cityTab();
        } else if (sty == 3) {
            countyTab();
        } else {
            villageTab();
        }
    }
}

//加载代表基本信息详情
function dbInfo(item) {
    var itemId = item.getAttribute('item-id');
    var urldb = '代表信息.html?id=' + itemId;
    window.open(urldb);
}

//tab页切换方法
function provTab() {
    $('#province').toggle();
    $('#tab1').attr('class', 'cur');
    $('#tab2').attr('class', 'unselect');
    $('#tab3').attr('class', 'unselect');
    $('#tab4').attr('class', 'unselect');
    $('#city').css('display', 'none');
    $('#county').css('display', 'none');
    $('#village').css('display', 'none');
}

function cityTab() {
    $('#city').toggle();
    $('#tab2').attr('class', 'cur');
    $('#tab1').attr('class', 'unselect');
    $('#tab3').attr('class', 'unselect');
    $('#tab4').attr('class', 'unselect');
    $('#province').css('display', 'none');
    $('#county').css('display', 'none');
    $('#village').css('display', 'none');
}

function countyTab() {
    $('#county').toggle();
    $('#tab3').attr('class', 'cur');
    $('#tab2').attr('class', 'unselect');
    $('#tab1').attr('class', 'unselect');
    $('#tab4').attr('class', 'unselect');
    $('#city').css('display', 'none');
    $('#province').css('display', 'none');
    $('#village').css('display', 'none');
}

function villageTab() {
    $('#village').toggle();
    $('#tab4').attr('class', 'cur');
    $('#tab2').attr('class', 'unselect');
    $('#tab3').attr('class', 'unselect');
    $('#tab1').attr('class', 'unselect');
    $('#city').css('display', 'none');
    $('#county').css('display', 'none');
    $('#province').css('display', 'none');
}

//取消键
function close1() {
    $('.float-1').css('display', 'none');
}

/**
 *
 * POI搜索
 */
//点击搜索tab页

//搜索结果
function clickSearchPIO() {
    // clearAll();
    // html=""; //清空搜索结果列表
    //获取输入框里面的值
    keyword = $('#keyWord').val();
    if (keyword != '' && keyword != undefined) {
        clearAll();
        html = ''; //清空搜索结果列表
        var url;
        if (tabNum == 1) {
            url =
                'https://ditu.zjzwfw.gov.cn:443/ime-server/rest/placesearch/place/search?&token=2c92920471b56e640171be7781500079';
        } else if (tabNum == 0) {
            url = './js/digitalPlatform/interfacelocation.json';
        }
        //解析返回的数据
        $.ajax({
            url: url,
            // url:'./js/digitalPlatform/interfacelocation.json',
            type: 'GET',
            data: {
                q: keyword
            },
            dataType: 'JSON',
            success: function (data) {
                //点聚合
                markers = L.markerClusterGroup({
                    //创建加载点位的变量
                    maxClusterRadius: 60,
                    //Disable all of the defaults:
                    spiderfyOnMaxZoom: false,
                    showCoverageOnHover: false,
                    zoomToBoundsOnClick: false
                });
                console.log(data);
                dataList = data.results;
                $.each(data.results, function (index, val) {
                    // console.log(val.name);
                    //POI搜索加载
                    if (tabNum == 1) {
                        html +=
                            '<div class="item" data-id=' +
                            val.id +
                            ' onclick="setClick(this)">' +
                            '                        <span class="icon"><svg version="1.1" role="presentation" width="13.714285714285714" height="13.714285714285714" viewbox="0 0 1024 1024" class="svg-icon active" style="font-size: 1.5em;"><path d="M354.461538 393.846154a157.538462 157.538462 0 1 1 315.076924 0 157.538462 157.538462 0 0 1-315.076924 0m551.384616 5.12C905.846154 178.569846 729.481846 0 512 0S118.153846 178.569846 118.153846 398.966154C118.153846 619.283692 442.368 1024 512 1024c57.974154 0 393.846154-404.716308 393.846154-625.033846z" stroke="transparent"></path></svg>' +
                            '                        </span><span class="text"><span class="name">' +
                            val.name +
                            '                        </span><span class="sub">' +
                            val.address +
                            '</span></span></div>';
                    } else if (tabNum == 0) {
                        if (val.llzName.indexOf(keyword) >= 0) {
                            html +=
                                '<div class="item" data-id=' +
                                val.id +
                                ' onclick="setClick(this)">' +
                                '                        <span class="icon"><svg version="1.1" role="presentation" width="13.714285714285714" height="13.714285714285714" viewbox="0 0 1024 1024" class="svg-icon active" style="font-size: 1.5em;"><path d="M354.461538 393.846154a157.538462 157.538462 0 1 1 315.076924 0 157.538462 157.538462 0 0 1-315.076924 0m551.384616 5.12C905.846154 178.569846 729.481846 0 512 0S118.153846 178.569846 118.153846 398.966154C118.153846 619.283692 442.368 1024 512 1024c57.974154 0 393.846154-404.716308 393.846154-625.033846z" stroke="transparent"></path></svg>' +
                                '                        </span><span class="text"><span class="name">' +
                                val.llzName +
                                '                        </span><span class="sub">' +
                                val.address +
                                '</span></span></div>';
                        }
                    }
                    if (html != '' && html != undefined) {
                        $('#nullResult').css('display', 'none');
                        $('#searchOptions').css('display', 'block');
                    } else {
                        $('#nullResult').css('display', 'block');
                        $('#searchOptions').css('display', 'none');
                    }
                    var lat = val.lat; //点的纬度
                    var lon = val.lon; //点的经度
                    if (lat && lon) {
                        var myIcon = L.icon({
                            iconUrl: '../css/img/map/marker-icon.png',
                            iconSize: [25, 41],
                            iconAnchor: [15, 40]
                        });
                        let marker = L.marker([lat, lon], {
                            icon: myIcon
                        });
                        marker.on('click', () => {
                            handleMapMarerClick(val);
                        });
                        markers.addLayer(marker);
                    }
                    map.addLayer(markers);
                    // $("#searchOptions").css("display","block");
                    $('#searchOptions').html(html);
                });
            }
        });
    }
}
//清空方法
function clearAll() {
    //清空地图方法
    if (markers != '' && markers != undefined) {
        map.removeLayer(markers);
    }
    $('#searchOptions .item').remove(); //清空搜索结果列表
    $('#searchOptions').css('display', 'none');
}
//点击搜索结果的方法
function setClick(param) {
    var param = param.getAttribute('data-id');
    //将标点结果集整体作为地图中心点
    /*

     */
    //遍历第一次列表搜索里的数据
    $.each(dataList, function (index, value) {
        var id = value.id;
        if (param == id) {
            var latLng = {
                lat: [value.lat],
                lon: [value.lon]
            };
            handleMapMarerClick(value); //点击结果选项后，触发标点的点击事件，跳转到该标记点上

            // if (tabNum==1){
            //     L.popup()
            //         .setLatLng([value.location.lat, value.location.lon])
            //         .setContent(value.name)
            //         .openOn(map);
            // }else if (tabNum==0){
            //     L.popup()
            //         .setLatLng([value.location.lat, value.location.lon])
            //         .setContent(value.llzName)
            //         .openOn(map);
            // }

            //跳转后，实现地图放大
            map.flyTo(latLng, 17);
            // map.setView(latLng, 17);
        }
    });
}